<template>
  <div>
    <el-table-form ref="form" class="form" :model="query">
      <el-form-item label="条件类型" class="merge-item" :table-form-merge="1.1">
        <el-select v-model="query.pType" class="mr10">
          <!-- <el-option label="订单号" value="1">订单号</el-option> -->
          <el-option label="客户电话" value="csmRgPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="客户地址" value="csmRgAddress" />
          <el-option label="身份证号" value="sfzh" />
          <el-option label="销售人员" value="salesManName" />
        </el-select>
        <el-input v-model="query.pText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="所属机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>

      <el-form-item label="开户时间" :table-form-merge="1.1" class="merge-item">
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="客户类型" class="merge-item">
        <el-select v-model="query.csmType">
          <el-option label="居民用户" value="1" />
          <el-option label="非居民用户" value="2" />
          <el-option label="工业用户" value="4" />
          <el-option label="瓶批用户" value="8" />
          <el-option label="槽批用户" value="16" />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-folder-add" @click="add">新增</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <EditorAddDialog
      ref="EditorAddDialogRef"
      :tree-data="treeData"
      :cms-type="cmsType"
      :cms-level="cmsLevel"
      @refresh="search"
    />
    <!-- <detailbottle ref="detail" /> -->
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { pickUpCustomerList, pickUpCustomerCancle, queryMap } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import dayjs from 'dayjs'

  export default {
    name: 'pickUpCustomer',
    components: {
      EditorAddDialog: require('./EditOrAddDialog').default
    },

    data() {
      return {
        treeData: [],
        cmsLevel: [
        // { value: 1, desc: "一级", key: "Level1" },
        // { value: 2, desc: "二级会员", key: "Level2" },
        // { value: 3, desc: "三级会员", key: "Level3" },
        ],
        cmsType: [
        // { value: 1, desc: "居民用户", key: "Resident_user" },
        // { value: 2, desc: "非居民用户", key: "Business_user" },
        // { value: 4, desc: "工业用户", key: "GY_user" },
        // { value: 8, desc: "瓶批用户", key: "BOTTLE_user" },
        // { value: 16, desc: "槽批用户", key: "GROOVE_user" },
        ],
        query: {
          pType: 'csmRgPhone',
          pText: '',
          date: [],
          csmType: ''
        },
        tableData: {
          data: [],
          total: 0
        },
        actionColWidth: 80
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column() {
        return [
          // { label: '自提客户ID', prop: 'csmPickupId', width: 80, hidden: true },
          { label: '客户编号', prop: 'csmCode', width: 130, align: 'center' },
          { label: '客户名称', prop: 'csmName', width: 100, align: 'center' },
          {
            label: '客户类型',
            prop: 'csmType',
            width: 100,
            align: 'center',
            formatter: this.csmTypeFormat
          },
          {
            label: '客户性质',
            prop: 'csmQuality',
            width: 100,
            align: 'center',
            formatter: this.csmQualityFormat
          },
          { label: '客户地址', prop: 'csmRgAddress', width: 200, align: 'center' },
          { label: '客户电话', prop: 'csmRgPhone', width: 100, align: 'center' },
          { label: '身份证号', prop: 'sfzh', width: 180, align: 'center' },
          { label: '所属机构', prop: 'orgName', width: 100, align: 'center' },
          { label: '销售人员', prop: 'salesManName', width: 100, align: 'center' },
          {
            label: '状态',
            prop: 'csmStatus',
            width: 100,
            align: 'center',
            render: (h, { row, column, $index }) => {
              return (
              <div style={`color:${this.getColor(row, column)}`}>
                {this.csmStatusFormat(row, column)}
              </div>
              )
            }
          },
          {
            label: '开户时间',
            prop: 'createTime',
            width: 130,
            align: 'center',
            formatter: this.dateTimeFormat
          },

          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
              <div>
                <el-link size='mini' onClick={() => this.edit(row, $index)}>
                  {row.csmStatus !== -1 ? '编辑' : ''}
                </el-link>
                <el-link
                  size='mini'
                  type='danger'
                  onClick={() => this.cancellation(row, $index)}
                >
                  {row.csmStatus === 2 ? '注销 ' : ''}
                </el-link>
              </div>
              )
            }
          }
        ]
      }
    },

    async created() {
      await this.getTreeData()
      await this.queryOptionsMap()
    },
    methods: {
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CustomerQuality' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })
        ])
        this.cmsLevel = res1.data // 客户登记
        this.cmsType = res2.data // 客户类型
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      csmTypeFormat: function(row, column, cellValue, index) {
        const val = row[column.property]
        if (!val) return
        const msg = this.cmsType.find((l) => l.value === val)

        return msg && msg.desc || ''
      },
      csmQualityFormat: function(row, column, cellValue, index) {
        const val = row[column.property]
        var msg = this.cmsLevel.find((l) => l.value === val)
        if (!msg) {
          return ''
        }
        return msg.desc
      },
      csmStatusFormat: function(row, column, cellValue, index) {
        const val = row[column.property]
        if (val === 1) {
          return '未审核'
        } else if (val === 2) {
          return '已审核'
        } else if (val === -1) {
          return '已注销'
        } else {
          return ''
        }
      },
      getColor(row, column) {
        const val = row[column.property]
        if (val === 1) {
          return '#EA8511'
        } else if (val === 2) {
          return ''
        } else if (val === -1) {
          return 'red'
        } else {
          return ''
        }
      },
      dateTimeFormat: function(row, column, cellValue, index) {
        const val = row[column.property]
        if (val) {
          return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
        } else {
          return ''
        }
      },

      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (query.date.length) {
          query.createTime = dayjs(query.date[0]).format('YYYY-MM-DD')
          query.createTimeEnd = dayjs(query.date[1]).format('YYYY-MM-DD')
        }
        if (this.query.pText) query[this.query.pType] = this.query.pText
        delete query.pText
        delete query.pType
        delete query.date
        const { status, data } = await pickUpCustomerList(query)
        if (status === 200) {
          this.tableData.data = data.rows
          if (currentPage === 1) this.tableData.total = data.total
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 新增
      add() {
        this.$refs.EditorAddDialogRef.show(1)
      },

      // 注销
      cancellation(row) {
        this.$confirm('您确定要注销该用户吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.cancellationSubmit(row)
          })
          .catch(() => {})
      },
      async cancellationSubmit(row) {
        const params = {
          csmPickupId: row.csmPickupId
        }
        const { status } = await pickUpCustomerCancle(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      },
      edit(row) {
        this.$refs.EditorAddDialogRef.show(2, row)
      }
    }
  }
</script>

<style scoped lang="scss">
.form {
  display: flex;
  flex-wrap: wrap;
  // justify-content: space-between;
  // & /deep/ .el-form-item {
  //   .el-form-item__content > .el-select {
  //     width: 100%;
  //   }
  // }
  // .block {
  //   width: 100%;
  // }
}
</style>
